package ink.xiaobaibai.common;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-07-26
 **/

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({Set.class})
@Component
public class RoomObjListHandler implements TypeHandler<Set> {

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Set set, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSON.toJSONString(set));
    }

    @Override
    public Set getResult(ResultSet resultSet, String s) throws SQLException {
        if ("[]".equals(resultSet.getString(s)) || StringUtils.isBlank(resultSet.getString(s))) {
            return new HashSet();
        }
        String string = resultSet.getString(s);
        List<RoomObj> roomObjs = JSON.parseArray(string, RoomObj.class);
        if (roomObjs.size() == 0) {
            return new HashSet();
        }
        return new HashSet<>(roomObjs);
    }

    @Override
    public Set getResult(ResultSet resultSet, int i) throws SQLException {
        if ("[]".equals(resultSet.getString(i)) || StringUtils.isBlank(resultSet.getString(i))) {
            return new HashSet();
        }
        List<RoomObj> roomObjs = JSON.parseArray(resultSet.getString(i), RoomObj.class);
        if (roomObjs.size() == 0) {
            return new HashSet();
        }
        return new HashSet<>(roomObjs);
    }

    @Override
    public Set getResult(CallableStatement callableStatement, int i) throws SQLException {
        if ("[]".equals(callableStatement.getString(i)) || StringUtils.isBlank(callableStatement.getString(i))) {
            return new HashSet();
        }
        List<RoomObj> roomObjs = JSON.parseArray(callableStatement.getString(i), RoomObj.class);
        if (roomObjs.size() == 0) {
            return new HashSet();
        }
        return new HashSet<>(roomObjs);
    }

}
